package cn.edu.zhku.shiro.realm;

import cn.edu.zhku.pojo.Menu;
import cn.edu.zhku.pojo.Role;
import cn.edu.zhku.pojo.Token;
import cn.edu.zhku.pojo.User;
import cn.edu.zhku.service.TokenService;
import cn.edu.zhku.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 授权 获取用户的角色和权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 1. 从PrincipalCollection中获取登录用户的信息
        User user = (User) principals.getPrimaryPrincipal();
        // 2.添加角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 2.1 添加角色
        Role role = user.getRole();
        info.addRole(role.getRoleKey());
        // 2.2 添加菜单权限
        List<Menu> menus = role.getMenus();
        for (Menu m : menus) {
            info.addStringPermission(m.getPermKey());
        }
        return info;
    }

    /**
     * 认证 判断token的有效性
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取token，即前端传入的token
        String accessToken = (String) token.getPrincipal();
        // 1. 根据accessToken ，查询用户信息
        Token tokenPojo = this.tokenService.findByToken(accessToken);
        // 2. token失效
        if (tokenPojo == null || tokenPojo.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new ExpiredCredentialsException("登录凭证已失效，请重新登录");
        }
        // 3. 从数据库中查询用户信息
        User user = this.userService.findUserRoleMenuByUserId(tokenPojo.getUserId());
        // 4. 用户不存在
        if (user == null) {
            throw new UnknownAccountException("用户名或密码错误，请重新登录");
        }
        // 5. 根据用户的情况，来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, this.getName());
        return info;
    }
}
